/**
 * BrandBigData.com Inc.
 * Copyright (c) 2016 All Rights Reserved.
 */
package com.qibao.toolkit;

import com.qibao.toolkit.exception.PythonExecuteException;
import com.qibao.toolkit.exception.PythonSyntaxException;
import com.qibao.toolkit.facade.ExecuteContext;
import com.qibao.toolkit.facade.PythonExecutorService;
import com.qibao.toolkit.util.JsonUtils;
import com.qibao.toolkit.util.PythonUtils;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author xumin
 * @version $Id:RemotePythonExecutorService.java, v0.1 2018/5/2 11:58 xumin
 */
public class RemotePythonExecutorService implements PythonExecutorService {
    private static final Logger logger = LoggerFactory.getLogger(RemotePythonExecutorService.class);

    private String pythonServiceUrl;

    public RemotePythonExecutorService(String pythonServiceUrl) {
        this.pythonServiceUrl = pythonServiceUrl;
    }

    @Override
    public String executeScript(String script, ExecuteContext executeContext) throws PythonExecuteException {
        try {
            script = replaceVariables(script);
            BasicNameValuePair file = new BasicNameValuePair("script", script);
            BasicNameValuePair variables = new BasicNameValuePair("variables", JsonUtils.writeValueAsString(executeContext.getParameters()));
            logger.debug("传递给python的variables入参：{}", variables.getValue());
            HttpEntity httpEntity = new UrlEncodedFormEntity(Lists.newArrayList(file, variables), Charsets.UTF_8);
            String result = Request.Post(pythonServiceUrl + "/execute_script").body(httpEntity).execute().returnContent().asString();
            ExecuteResponse executeResponse = JsonUtils.readValue(result, ExecuteResponse.class);
            if (!executeResponse.isSuccess()) {
                throw new PythonExecuteException(executeResponse.getErrorMsg());
            }
            logger.debug("python脚本执行结果：" + executeResponse.getResult());
            return executeResponse.getResult();
        } catch (Exception e) {
            throw new PythonExecuteException(e.getMessage(), e);
        }
    }

    private String replaceVariables(String script) {
        List<String> variables = PythonUtils.extractVariables(script);
        for (String variable : variables) {
            script = StringUtils.replace(script, "{" + variable + "}", variable);
        }
        return script;
    }

    @Override
    public List<String> extractVariables(String script) throws PythonSyntaxException {
        return PythonUtils.extractVariables(script);
    }


}
